package part2.solution146;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: shaochong
 * @Date: 2021/8/16
 * @Description:
 */
public class LRUCache {

    // 双向链表节点
    class DLinkedNode {
        int key;
        int value;
        DLinkedNode next;
        DLinkedNode prev;
        public DLinkedNode() {}
        public DLinkedNode(int _key, int _value) {
            key = _key;
            value = _value;
        }
    }

    private Map<Integer, DLinkedNode> cache = new HashMap<>();
    // 大小
    private int size;
    // 容量
    private int capacity;
    // 链表的头尾指针
    private DLinkedNode head, tail;

    public LRUCache(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        // 使用伪头部和伪尾部节点
        head = new DLinkedNode();
        tail = new DLinkedNode();
        head.next = tail;
        tail.prev = head;
    }

    public int get(int key) {
        DLinkedNode node = cache.get(key);
        if (node == null) {
            return -1;
        }
        // 访问过,移动到首位
        moveToHead(node);
        return node.value;
    }

    public void put(int key, int value) {
        DLinkedNode node = cache.get(key);
        if (node == null) {
            DLinkedNode newNode = new DLinkedNode(key, value);
            // 加入map
            cache.put(key, newNode);
            // 放入链表首位
            addToHead(newNode);
            // 大小+1
            size++;
            if (size > capacity) {
                // 容量太大,删除尾部元素
                DLinkedNode tail = removeTail();
                // 删除map
                cache.remove(tail.key);
                // 调整大小
                size--;
            }
        } else {
            node.value = value;
            moveToHead(node);
        }
    }

    private void addToHead(DLinkedNode node) {
        node.prev = head;
        node.next = head.next;
        head.next.prev = node;
        head.next = node;
    }

    private void removeNode(DLinkedNode node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void moveToHead(DLinkedNode node) {
        removeNode(node);
        addToHead(node);
    }

    private DLinkedNode removeTail() {
        DLinkedNode res = tail.prev;
        removeNode(res);
        return res;
    }



    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);
        cache.put(1 ,1);
        System.out.println(cache.get(1));
    }



}
